﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using System.Windows.Media;

namespace Sker.Controls
{
    public static class Util
    {
        /// <summary>Checks if a string has some value or is null.</summary>
        /// <param name="string">The string to check.</param>
        /// <returns>False if it's null or empty, true otherwise.</returns>
        /// <remarks>This is a wrapper for IsNullOrEmpty.</remarks>
        public static bool HasValue(this string value)
        {
            return !string.IsNullOrEmpty(value);
        }

        /// <summary>Gives focus to the calling element. This one actually works.</summary>
        /// <param name="element">Element that will receive focus.</param>
        public static void FocusThatWorks(this UIElement element)
        {
            element.Dispatcher.BeginInvoke((Action)(() =>
            {
                element.Focus();
                Keyboard.Focus(element);
            }), DispatcherPriority.Render);
        }

        /// <summary>Searches the visual tree of a control and returns the first element specified by the generic type.</summary>
        /// <typeparam name="T">The type of element to be found.</typeparam>
        /// <param name="obj">The object under which the search will start.</param>
        /// <returns>The element or null</returns>
        public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                var child = VisualTreeHelper.GetChild(obj, i);

                if (child != null && child is T)
                {
                    return child as T;
                }
                else
                {
                    T childOfChild = FindVisualChild<T>(child);
                    if (childOfChild != null)
                    {
                        return childOfChild;
                    }
                }
            }
            return null;
        }
    }
}
